package com.server.start;

import com.register.client.domian.ClientServiceInstance;
import com.register.client.domian.HeartBeat;
import com.register.client.domian.Response;
import com.server.entity.HeartbeatCounter;
import com.server.entity.Registry;
import com.server.entity.ServiceInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.atomic.LongAdder;

/**
 * 主要用于server的查询
 */
@RestController
@RequestMapping("/query")
public class CaptainServerQuery {

    public static final Logger log = LoggerFactory.getLogger(CaptainServerQuery.class);


    /**
     * 发送心跳
     *
     * @param heartBeat
     * @return
     */
    @PostMapping("/heartBeat")
    public Response heartBeat(@RequestBody HeartBeat heartBeat) {
        //1.检查服务注册表中是否存在服务实例
        Registry instance = Registry.getInstance();
        ServiceInstance serviceInstance = instance.getServiceInstance(heartBeat);
        if (serviceInstance != null) {
            //更新心跳时间
            serviceInstance.getLease().renew();
            //更新最近一分钟的心跳数
            HeartbeatCounter.getInstance().increment();
            return Response.SUCCESS;
        }
        //服务实例不存在
        log.error("心跳续约报错,服务实例不存在{}", heartBeat.getServerName());
        return Response.FAILE;
    }

    /**
     * client拉取全量的注册表
     *
     * @return
     */
    @GetMapping("/fetchServiceRegistry")
    public Map<String, Map<String, ClientServiceInstance>> fetchServiceRegistry() {
        // 获取service中的注册表
        Map<String, Map<String, ServiceInstance>> registryMap = Registry.getInstance().getRegistryMap();

        Map<String, Map<String, ClientServiceInstance>> registry = processRegistry(registryMap);

        return registry;
    }

    @GetMapping("/fetchDeltaServiceRegistry")
    public Map<String, Map<String, ClientServiceInstance>> fetchIncrementalServiceRegistry() {
        Map<String, Map<String, ClientServiceInstance>> incrementalRegistryMap = Registry.getInstance().getIncrementalRegistryMap();
        return incrementalRegistryMap;
    }



    /**
     * 处理数据
     *
     * @param registryMap
     * @return
     */
    private Map<String, Map<String, ClientServiceInstance>> processRegistry(Map<String, Map<String, ServiceInstance>> registryMap) {
        Map<String, Map<String, ClientServiceInstance>> registry = new HashMap<>();
        if (registryMap.keySet().size() > 0) {
            Set<String> serviceNames = registryMap.keySet();
            for (String serviceName : serviceNames) {
                Map<String, ServiceInstance> serviceInstanceMap = registryMap.get(serviceName);
                Collection<ServiceInstance> serviceInstances = serviceInstanceMap.values();
                Map<String, ClientServiceInstance> clientCachedServiceRegistryMap = new HashMap<>();
                for (ServiceInstance serviceInstance : serviceInstances) {
                    ClientServiceInstance clientServiceInstance = new ClientServiceInstance();
                    BeanUtils.copyProperties(serviceInstance, clientServiceInstance);
                    clientCachedServiceRegistryMap.put(serviceInstance.getServiceInstanceId(), clientServiceInstance);
                }
                registry.put(serviceName, clientCachedServiceRegistryMap);
            }

            return registry;

        }
        return null;
    }

}
